import { PLUGIN_HEADING } from './options.js'
import Plugin from './plugin.js'
export default class HeadingPlugin extends Plugin {
    constructor(name, editor) {
        super(name, editor)
        this._config = PLUGIN_HEADING
        this._format = 'div'
        this._init()
    }

    getDom() {
        return this._plugin
    }

    _init() {
        this._createForm()
    }

    _createPopover() {
        const popover = document.createElement('div')
        popover.classList.add('plugin-popover', 'plugin-popover-heading')
        const defaultFormat = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div']
        const defaultFormatText = ['标题 1', '标题 2', '标题 3', '标题 4', '标题 5', '标题 6', '文本']
        popover.innerHTML = `<div>
            <ul class="plugin-default-format clear-fix"></ul>
        </div>`
        defaultFormat.forEach((format, index) => {
            const li = document.createElement('li')
            const formatBlock = document.createElement(format)
            formatBlock.innerText = defaultFormatText[index]
            formatBlock.title = defaultFormatText[index]
            li.dataset.format = format
            li.appendChild(formatBlock)
            popover.querySelector('.plugin-default-format').appendChild(li)
        })
        popover.querySelector('.plugin-default-format').addEventListener('mousedown', e => {
            let { target } = e
            while (target.tagName.toUpperCase() !== 'LI') {
                target = target.parentNode
            }
            this._format = target.dataset.format
            console.log(target)
            e.preventDefault()
            this._execCommand()
        })
        return popover
    }

    _getPopover() {
        if (!this._popover) {
            this._popover = this._createPopover()
            this._$editor._editor.appendChild(this._popover)
        }
        return this._popover
    }

    _createForm() {
        this._plugin = document.createElement('li')
        this._plugin.classList.add('plugin-trigger')
        this._plugin.innerHTML = this._config.content
        this._plugin.title = this._config.name
        this._plugin.addEventListener('mousedown', (e) => {
            e.preventDefault()
            this._plugin.classList.toggle('plugin-active')
            const bound = this._plugin.getBoundingClientRect()
            const top = ~~('top' in bound ? bound.top : bound.y) + 25
            const left = ~~('left' in bound ? bound.left : bound.x) - 1
            const popover = this._getPopover()
            popover.style.cssText += `top:${top}px;left:${left}px`
            popover.classList.toggle('plugin-popover-active')
        })
    }

    _execCommand() {
        this._command.setFormatBlock(this._format)
        this._popover.classList.toggle('plugin-popover-active')
    }
}